<html>
<head>

<title>Groovy Goodness: Static Imports</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Static Imports</h3>

<div class="post">
<p>Java already has static imports, but Groovy takes it to the <a href="http://groovy.codehaus.org/Static+Import+Usage">next level</a>. In a <a href="http://mrhaki.blogspot.com/2009/09/groovy-goodness-as-keyword.html">previous post</a> we learned how we use the <code>as</code> keyword to assign a class we import to a variable in the <code>import</code> statement. But with static imports we can do this even for static methods and properties. This makes for code which may confuse us, but if we look at the import section all will be revealed.</p>
<pre class="brush:groovy">
import static HttpURLConnection.HTTP_OK  // Normal Java static import.
import static HttpURLConnection.HTTP_OK as okay 
import static HttpURLConnection.setFollowRedirects as redirect
import java.net.HttpURLConnection as http // Non static import.

redirect false  // HttpURLConnection.setFollowRedirects(false)
assert false == HttpURLConnection.followRedirects

def c = (http) 'http://mrhaki.blogspot.com'.toURL().openConnection()
assert c instanceof HttpURLConnection

assert okay == c.responseCode
assert HTTP_OK == c.responseCode
</pre
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>